package com.glebusheg.ui
{
	import com.glebusheg.asset.AssetLoader;
	import com.glebusheg.asset.AssetManager;
	import com.glebusheg.data.AppData;
	import com.glebusheg.data.Item;
	import com.glebusheg.utils.VisualUtil;
	import flash.display.Bitmap;
	import flash.display.Sprite;
	import flash.events.Event;
	
	/**
	 * ...
	 * @author Gleb Volkov
	 */
	public class IconControl implements IWrappable
	{
		private var _content:Sprite;
		
		private var _icon:Bitmap;
		private var _iconDef:String;
		private var _iconHolder:Sprite;
		private var _iconLoader:AssetLoader;
		private var _item:Item;
		
		private var _onLoad:Function;
		//private var _iconProxy:LazyLoaderComponent;
		
		public function IconControl(content:Sprite)
		{
			_content = content;
			
			_iconHolder = content as Sprite;
			VisualUtil.clear(_iconHolder);
			_iconHolder.mouseChildren = false;
			_iconHolder.mouseEnabled = false;
		}
		
		public function loadItem(item:Item):void
		{
			var def:String;
			
			if (item)
			{
				_item = item;
				def = item.info.iconResource;
			}
			
			loadIcon(def);
		}
		
		public function loadItemByName(name:String):void
		{
			var item:Item;
			var def:String;
			
			if (AppData.hasItem(name))
			{
				item = AppData.getItem(name);
				if (item)
					def = item.info.iconResource;
			}
			
			loadIcon(def);
		}
		
		public function loadIcon(resource:String):void
		{
			if (!_iconHolder)
				return;
			
			if (_icon)
			{
				_iconHolder.removeChild(_icon);
				_icon = null;
			}
			
			if (_iconLoader)
			{
				_iconLoader.removeEventListener(Event.COMPLETE, onIconLoaded);
				_iconLoader = null;
			}
			
			_iconDef = resource;
			if (_iconDef)
			{
				_iconLoader = AssetManager.load(_iconDef);
				if (_iconLoader)
				{
					/*if(!_iconProxy)
					 _iconProxy = new LazyLoaderComponent(this, _iconHolder);*/
					
					_iconLoader.addEventListener(Event.COMPLETE, onIconLoaded);
					_iconLoader.load();
				}
			}
			
			if (!_iconLoader)
				onIconLoaded(null);
		}
		
		private function onIconLoaded(event:Event):void
		{
			/*if(_iconProxy)
			   {
			   _iconProxy.destroy();
			   _iconProxy = null;
			   _iconLoader = null;
			 }*/
			
			if (_iconDef)
				_icon = new Bitmap(AssetManager.getBitmapData(_iconDef));
			
			if (_icon)
			{
				if (_onLoad != null)
					_onLoad(Bitmap(_icon));
				
				_iconHolder.addChild(_icon);
			}
		}
		
		public function get item():Item
		{
			return _item;
		}
		
		public function set onLoad(value:Function):void
		{
			_onLoad = value;
		}
		
		public function destroy():void 
		{
			
		}
		
		/* INTERFACE com.glebusheg.ui.IWrappable */
		
		public function get content():Sprite
		{
			return _content;
		}
	}
}